package com.jhs.boot.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhs.boot.common.beans.Common;
import com.jhs.boot.config.FeignClientFactory;
import com.jhs.boot.system.converter.SysRouteConverter;
import com.jhs.boot.system.mapper.SysNodesMapper;
import com.jhs.boot.system.mapper.SysRouteMapper;
import com.jhs.boot.system.model.entity.SysNodeRoute;
import com.jhs.boot.system.model.entity.SysNodes;
import com.jhs.boot.system.model.entity.SysRoute;
import com.jhs.boot.system.model.form.SysRouteForm;
import com.jhs.boot.system.model.query.SysRouteQuery;
import com.jhs.boot.system.model.vo.SysRouteVO;
import com.jhs.boot.system.service.SysNodeRouteService;
import com.jhs.boot.system.service.SysRouteService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 节路由服务实现类
 *
 * @author zxy
 * @since 2025-11-22 10:18
 */
@Service
@RequiredArgsConstructor
public class SysRouteServiceImpl extends ServiceImpl<SysRouteMapper, SysRoute> implements SysRouteService {

    private final SysRouteConverter sysRouteConverter;

    private final FeignClientFactory feignClientFactory;

    private final SysNodeRouteService sysNodeRouteService;

    private final SysNodesMapper sysNodesMapper;

    private final StringRedisTemplate redisTemplate;


    /**
    * 获取节路由分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<SysRouteVO>} 节路由分页列表
    */
    @Override
    public IPage<SysRouteVO> getSysRoutePage(SysRouteQuery queryParams) {
        Page<SysRouteVO> pageVO = this.baseMapper.getSysRoutePage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取节路由表单数据
     *
     * @param id 节路由ID
     * @return 节路由表单数据
     */
    @Override
    public SysRouteForm getSysRouteFormData(Long id) {
        SysRoute entity = this.getById(id);
        return sysRouteConverter.toForm(entity);
    }
    
    /**
     * 新增节路由
     *
     * @param formData 节路由表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveSysRoute(SysRouteForm formData) {
        SysRoute entity = sysRouteConverter.toEntity(formData);
        boolean save = this.save(entity);
        if (save){
            String baseUrl = Common.HTTP + formData.getRouteIp() + ":" + formData.getPort();
            feignClientFactory.getFeignClient(baseUrl);
        }
        return save;
    }
    
    /**
     * 更新节路由
     *
     * @param id   节路由ID
     * @param formData 节路由表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateSysRoute(Long id,SysRouteForm formData) {
        SysRoute byId = this.getById(id);
        String oldUrl = Common.HTTP + byId.getRouteIp() + ":" + byId.getPort();
        String newUrl = Common.HTTP + formData.getRouteIp() + ":" + formData.getPort();
        SysRoute entity = sysRouteConverter.toEntity(formData);
        entity.setUpdateTime(LocalDateTime.now());
        boolean updateById = this.updateById(entity);
        if (updateById){
            feignClientFactory.refreshFeignClient(oldUrl,newUrl);
        }
        return updateById;
    }
    
    /**
     * 删除节路由
     *
     * @param ids 节路由ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteSysRoutes(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的节路由数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        List<SysRoute> sysRoutes = this.listByIds(idList);
        //删除redis
        List<SysNodes> byRouteId = sysNodesMapper.getByRouteId(idList);
        boolean removeByIds = this.removeByIds(idList);
        if (removeByIds){
            //删除关联表
            sysNodeRouteService.deleteSysNodeRoutes(ids);
            //删除三方调用链接
            for (SysRoute sysRoute:sysRoutes){
                String oldUrl = Common.HTTP + sysRoute.getRouteIp() + ":" + sysRoute.getPort();
                feignClientFactory.removeFeignClient(oldUrl);
            }

            byRouteId.stream().forEach(sysNodes -> redisTemplate.delete(Common.ROUTE+sysNodes.getIp()));

        }
        return removeByIds;
    }

    @Override
    public List<Long> getRouteNodesIds(Long routeId) {
        return  sysNodeRouteService.listRouteNodesIds(routeId);
    }

    /**
     * 路由分配权限
     * @param routeId
     * @param nodesId
     */
    @Override
    @Transactional
    public void assignRoutesToNodes(Long routeId, List<Long> nodesId){
        SysRoute byId = this.getById(routeId);
        if (byId == null) {
            throw new RuntimeException("路由不存在");
        }
        //分配路由前查看下要绑定的新节点是否在关系表中 如果在不允许绑定
        long count = sysNodeRouteService.count(new LambdaQueryWrapper<SysNodeRoute>().in(SysNodeRoute::getNodeId, nodesId));
        if (count>0){
            throw new RuntimeException("节点已经被绑定，请挑选其他节点或删除节点绑定的路由重新分配");
        }
        //一个路由IP只能分配一个节点
        Long mppCount = sysNodesMapper.selectCount(new LambdaQueryWrapper<SysNodes>().in(SysNodes::getId, nodesId).eq(SysNodes::getType, Common.ZERO));
        if (mppCount>1){
            throw new RuntimeException("一个路由只能分配一个MPP节点，请重新分配");
        }
        //查询routeid绑定的设备节点
        List<SysNodes> nodeOldlist =sysNodesMapper.getByRouteId(Collections.singletonList(routeId));
        //查询routeid绑定的设备新节点
        List<SysNodes> nodesNewList = sysNodesMapper.selectBatchIds(nodesId);
        //删除redis ROUTE-ip
        nodeOldlist.stream().forEach(sysNodes -> redisTemplate.delete(Common.ROUTE+sysNodes.getIp()));
        sysNodeRouteService.remove(new LambdaQueryWrapper<SysNodeRoute>()
                .eq(SysNodeRoute::getRouteId,routeId));
        if (CollectionUtil.isNotEmpty(nodesId)){
            List<SysNodeRoute> list = nodesId.stream()
                    .map(nodeId -> new SysNodeRoute(routeId, nodeId)).toList();
            sysNodeRouteService.saveBatch(list);
            //添加新的设备节点和路由的关系
            nodesNewList.stream().forEach(sysNodes -> redisTemplate.opsForValue().set(Common.ROUTE+sysNodes.getIp(), JSONUtil.toJsonStr(byId)));
        }
    }
}
